package com.danskin.wechat.webapi;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.danskin.wechat.api.client.DanskinCRMApiClient;
import com.danskin.wechat.constant.DanskinConstants;
import com.danskin.wechat.dto.CRMMemberRequest;
import com.danskin.wechat.entity.CrmBrandInfo;
import com.danskin.wechat.entity.CustCouponRecord;
import com.danskin.wechat.entity.CustInfo;
import com.danskin.wechat.entity.CustInfoEx;
import com.danskin.wechat.entity.CustOrderDetail;
import com.danskin.wechat.entity.CustOrderPayment;
import com.danskin.wechat.entity.CustOrderRecord;
import com.danskin.wechat.entity.CustPointRecord;
import com.danskin.wechat.entity.WxCardConfig;
import com.danskin.wechat.entity.WxMediaPlatform;
import com.danskin.wechat.model.AccessResponse;
import com.danskin.wechat.service.CouponService;
import com.danskin.wechat.service.CrmBrandInfoService;
import com.danskin.wechat.service.CustInfoService;
import com.danskin.wechat.service.CustOrderRecordService;
import com.danskin.wechat.service.CustPointRecordService;
import com.danskin.wechat.service.WxCardConfigService;
import com.danskin.wechat.util.BeanUtil;
import com.danskin.wechat.util.DateTools;
import com.danskin.wechat.util.DateUtils;
import com.danskin.wechat.util.EncryptUtil;
import com.danskin.wechat.util.LogUtil;
import com.danskin.wechat.util.StringUtil;

@RestController
@RequestMapping("api")
public class CrmDataApiController extends BaseApiController {

	@Autowired
	public CustInfoService custInfoService;

	@Autowired
	public CrmBrandInfoService crmBrandInfoService;

	@Autowired
	public CustPointRecordService custPointRecordService;

	@Autowired
	public CouponService couponService;
	@Autowired
	public WxCardConfigService cardConfigService;

	@Autowired
	public CustOrderRecordService custOrderRecordService;

	@Value("${crm_api_secret}")
	private String CRM_API_SECRET;

	/**
	 * 新增会员信息
	 * 
	 * @param map
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "AddMemberCTW", method = RequestMethod.POST)
	public Object addMemberCTW(@RequestBody Map<String, Object> map, HttpServletRequest request) {
		JSONObject validSecret = validSecret(map);
		if (validSecret != null) {
			return validSecret;
		}
		if (false == this.isValid("memberJSONList", map)) {
			return this.getError("memberJSONList不能为空");
		}
		Map<String, Object> json = (Map<String, Object>) (map.get("memberJSONList"));
		if (json != null) {
			if (false == this.isValid("brand", json)) {
				return this.getError("brand不能为空");
			}
			if (false == this.isValid("memberId", json)) {
				return this.getError("memberId不能为空");
			}
			if (false == this.isValid("mobileNum", json)) {
				return this.getError("mobileNum不能为空");
			}
			if (false == this.isValid("memberLevel", json)) {
				return this.getError("memberLevel不能为空");
			}
			CrmBrandInfo brandInfo = crmBrandInfoService.getCrmBrandInfo(this.getMapValue("brand", json));
			if (brandInfo == null) {
				return this.getError("品牌不存在");
			}

			CustInfo custInfo = new CustInfo();
			custInfo.setMemberId(this.getMapValue("memberId", json));
			custInfo.setMobile(this.getMapValue("mobileNum", json));
			custInfo.setName(this.getMapValue("fullName", json));
			custInfo.setIdCardNo(this.getMapValue("idNum", json));
			custInfo.setQq(this.getMapValue("qqNum", json));
			custInfo.setHobby(this.getMapValue("hobby", json));
			custInfo.setProvince(this.getMapValue("province", json));
			custInfo.setCity(this.getMapValue("city", json));
			custInfo.setAddress(this.getMapValue("address", json));
			custInfo.setIncome(this.getMapValue("income", json));
			custInfo.setJob(this.getMapValue("job", json));
			String gender = this.getMapValue("gender", json);
			if (!StringUtil.isNullOrEmpty(gender)) {

				custInfo.setGender(gender.equals("男") ? 1 : 2);
			} else {
				custInfo.setGender(0);
			}
			String birthday = this.getMapValue("birthday", json);
			if (!StringUtil.isNullOrEmpty(birthday)) {
				custInfo.setBirthday(DateUtils.str2Date(birthday));
			}
			custInfo.setSource(1);// 来源crm

			CustInfoEx custInfoEx = new CustInfoEx();
			custInfoEx.setVipLevel(this.getMapValue("memberLevel", json));
			custInfoEx.setMpId(brandInfo.getMpId());

			int rows = custInfoService.saveCustInfo(custInfo, custInfoEx);
			if (rows == -1) {
				return new AccessResponse<Object>("-1", "错误：该会员已存在。");
			}
			return new AccessResponse<Object>("0", "ok");
		} else {
			return this.getError("数据格式无效");
		}
	}

	/**
	 * 修改会员信息
	 * 
	 * @param map
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "ModifyMemberCTW", method = RequestMethod.POST)
	public Object modifyMemberCTW(@RequestBody Map<String, Object> map, HttpServletRequest request) {
		JSONObject validSecret = validSecret(map);
		if (validSecret != null) {
			return validSecret;
		}

		if (false == this.isValid("memberJSONList", map)) {
			return this.getError("memberJSONList不能为空");
		}
		Map<String, Object> json = (Map<String, Object>) (map.get("memberJSONList"));
		if (json != null) {

			if (false == this.isValid("brand", json)) {
				return this.getError("brand不能为空");
			}
			if (false == this.isValid("memberId", json)) {
				return this.getError("memberId不能为空");
			}
			if (false == this.isValid("mobileNum", json)) {
				return this.getError("mobileNum不能为空");
			}
			if (false == this.isValid("memberLevel", json)) {
				return this.getError("memberLevel不能为空");
			}
			CrmBrandInfo brandInfo = crmBrandInfoService.getCrmBrandInfo(this.getMapValue("brand", json));
			if (brandInfo == null) {
				return this.getError("品牌不存在");
			}

			CustInfo custInfo = new CustInfo();
			custInfo.setMemberId(this.getMapValue("memberId", json));
			custInfo.setMobile(this.getMapValue("mobileNum", json));
			custInfo.setName(this.getMapValue("fullName", json));
			custInfo.setIdCardNo(this.getMapValue("idNum", json));
			custInfo.setQq(this.getMapValue("qqNum", json));
			custInfo.setHobby(this.getMapValue("hobby", json));
			custInfo.setProvince(this.getMapValue("province", json));
			custInfo.setCity(this.getMapValue("city", json));
			custInfo.setAddress(this.getMapValue("address", json));
			custInfo.setIncome(this.getMapValue("income", json));
			custInfo.setJob(this.getMapValue("job", json));
			String gender = this.getMapValue("gender", json);
			if (!StringUtil.isNullOrEmpty(gender)) {
				custInfo.setGender(gender.equals("男") ? 1 : 2);
			} else {
				custInfo.setGender(0);
			}
			String birthday = this.getMapValue("birthday", json);
			if (!StringUtil.isNullOrEmpty(birthday)) {
				custInfo.setBirthday(DateUtils.str2Date(birthday));
			}

			CustInfoEx custInfoEx = new CustInfoEx();
			custInfoEx.setMpId(brandInfo.getMpId());
			custInfoEx.setVipLevel(this.getMapValue("memberLevel", json));
			// String validIntergral = this.getMapValue("validIntergral", json);
			// if (!StringUtil.isNullOrEmpty(validIntergral)) {
			// custInfoEx.setAvaPoints(Integer.valueOf(validIntergral));
			// }
			// String totalIntergral = this.getMapValue("totalIntergral", json);
			// if (!StringUtil.isNullOrEmpty(totalIntergral)) {
			// custInfoEx.setTotalPoints(Integer.valueOf(totalIntergral));
			// }

			WxMediaPlatform mp = this.getMPWithAccessToken(brandInfo.getMpId());
			int rows = custInfoService.updateCustInfo(mp, custInfo, custInfoEx);

			if (rows == -1) {
				return new AccessResponse<Object>("-1", "错误：该会员不存在。");
			}
			return new AccessResponse<Object>("0", "ok");
		} else {
			return this.getError("数据格式无效");
		}

	}

	/**
	 * 会员消费订单数据接收
	 * 
	 * @param map
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "SendCRMTradeInfo", method = RequestMethod.POST)
	public Object sendCRMTradeInfo(@RequestBody Map<String, Object> map, HttpServletRequest request) throws Exception {
		JSONObject validSecret = validSecret(map);
		if (validSecret != null) {
			return validSecret;
		}

		if (false == this.isValid("orderJSONList", map)) {
			return this.getError("orderJSONList不能为空");
		}
		Map<String, Object> json = (Map<String, Object>) (map.get("orderJSONList"));
		if (json != null) {

			if (false == this.isValid("brand", json)) {
				return this.getError("brand不能为空");
			}
			if (false == this.isValid("memberId", json)) {
				return this.getError("memberId不能为空");
			}
			if (false == this.isValid("customerMobile", json)) {
				return this.getError("customerMobile不能为空");
			}
			if (false == this.isValid("orderCode", json)) {
				return this.getError("orderCode不能为空");
			}
			if (false == this.isValid("orderType", json)) {
				return this.getError("orderType不能为空");
			}
			if (false == this.isValid("orderSource", json)) {
				return this.getError("orderSource不能为空");
			}
			if (false == this.isValid("storeCode", json)) {
				return this.getError("storeCode不能为空");
			}
			if (false == this.isValid("orderTotalAmount", json)) {
				return this.getError("orderTotalAmount不能为空");
			}
			if (false == this.isValid("payAmount", json)) {
				return this.getError("payAmount不能为空");
			}
			if (false == this.isValid("createDate", json)) {
				return this.getError("createDate不能为空");
			}
			if (false == this.isValid("productJsonList", json)) {
				return this.getError("productJsonList不能为空");
			}
			// if (false == this.isValid("paymentJsonList", json)) {
			// return this.getError("paymentJsonList不能为空");
			// }

			CrmBrandInfo brandInfo = crmBrandInfoService.getCrmBrandInfo(this.getMapValue("brand", json));
			if (brandInfo == null) {
				return this.getError("品牌不存在");
			}

			CustOrderRecord entity = new CustOrderRecord();
			entity.setMemberId(this.getMapValue("memberId", json));
			entity.setCustomerMobile(this.getMapValue("customerMobile", json));
			entity.setOrderNo(this.getMapValue("orderCode", json));
			entity.setType(this.getMapValue("orderType", json));
			entity.setSource(this.getMapValue("orderSource", json));
			entity.setStoreCode(this.getMapValue("storeCode", json));

			entity.setTotalAmount(new BigDecimal(this.getMapValue("orderTotalAmount", json)));
			entity.setPayAmount(new BigDecimal(this.getMapValue("payAmount", json)));

			String startDate = this.getMapValue("createDate", json);
			if (!StringUtil.isNullOrEmpty(startDate)) {
				Date d = DateUtils.str2Date(startDate);
				entity.setTransTime(d);
				entity.setTransYear(DateUtils.getYear(d));
			}

			List<CustOrderDetail> detailList = new ArrayList<CustOrderDetail>();
			List<Map<String, Object>> productJsonList = (List<Map<String, Object>>) (json.get("productJsonList"));
			if (productJsonList != null && productJsonList.size() > 0) {
				for (Map<String, Object> mapDetail : productJsonList) {

					CustOrderDetail detail = new CustOrderDetail();
					detail.setProductCode(this.getMapValue("productCode", mapDetail));
					String productName = this.getMapValue("productName", mapDetail);
					if (StringUtil.isNullOrEmpty(productName)) {
						productName = this.getMapValue("productCode", mapDetail);
					}
					detail.setProductName(productName);
					detail.setColorName(this.getMapValue("colorCode", mapDetail));
					detail.setColorCode(this.getMapValue("colorCode", mapDetail));

					String size = this.getMapValue("size", mapDetail);
					detail.setSize(this.handleSize(size));
					detail.setPrice(new BigDecimal(this.getMapValue("unitPrice", mapDetail)));
					detail.setQuantity(Integer.valueOf(this.getMapValue("qty", mapDetail)));
					detail.setTotalPrice(new BigDecimal(this.getMapValue("totalPrice", mapDetail)));

					detailList.add(detail);
				}
			}

			List<CustOrderPayment> paymentList = new ArrayList<CustOrderPayment>();
			// List<Map<String, Object>> paymentJsonList = (List<Map<String,
			// Object>>) (json.get("paymentJsonList"));
			// if (paymentJsonList != null && paymentJsonList.size() > 0) {
			// for (Map<String, Object> mapPayment : paymentJsonList) {
			// String paymentName = this.getMapValue("paymentName", mapPayment);
			// if (StringUtil.isNullOrEmpty(paymentName)) {
			// return this.getError("paymentName不能为空");
			// }
			// CustOrderPayment payment = new CustOrderPayment();
			// payment.setPaymentName(paymentName);
			// payment.setTotalCount(Integer.valueOf(this.getMapValue("totalCounts",
			// mapPayment)));
			// payment.setTotalAmount(new
			// BigDecimal(this.getMapValue("totalAmount", mapPayment)));
			//
			// paymentList.add(payment);
			// }
			// }

			WxMediaPlatform mp = this.getMPWithAccessToken(brandInfo.getMpId());
			int rows = custOrderRecordService.saveCustOrderRecord(mp, entity, detailList, paymentList);

			if (rows == -1) {
				return new AccessResponse<Object>("-1", "错误：该会员不存在。");
			}
			return new AccessResponse<Object>("0", "ok");
		} else {
			return this.getError("数据格式无效");
		}

	}

	/**
	 * 处理尺寸信息
	 * 
	 * @param size
	 * @return
	 */
	private String handleSize(String size) {

		if (!StringUtil.isNullOrEmpty(size)) {
			String size2 = size.replaceFirst("^0*", "");
			if (size2.equals("")) {
				return size;
			}
			return size2;
		}
		return "无";
	}

	/**
	 * 会员积分数据接收
	 * 
	 * @param map
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "ModifyIntergralCTP", method = RequestMethod.POST)
	public Object modifyIntergralCTP(@RequestBody Map<String, Object> map, HttpServletRequest request)
			throws ParseException {
		JSONObject validSecret = validSecret(map);
		if (validSecret != null) {
			return validSecret;
		}

		if (false == this.isValid("changeJSONList", map)) {
			return this.getError("changeJSONList不能为空");
		}
		Map<String, Object> json = (Map<String, Object>) (map.get("changeJSONList"));
		if (json != null) {

			if (false == this.isValid("brand", json)) {
				return this.getError("brand不能为空");
			}
			if (false == this.isValid("memberId", json)) {
				return this.getError("memberId不能为空");
			}
			if (false == this.isValid("changeId", json)) {
				return this.getError("changeId不能为空");
			}
			if (false == this.isValid("value", json)) {
				return this.getError("value不能为空");
			}
			if (false == this.isValid("getDate", json)) {
				return this.getError("getDate不能为空");
			}
			if (false == this.isValid("expiredDate", json)) {
				return this.getError("expiredDate不能为空");
			}
			if (false == this.isValid("validIntergral", json)) {
				return this.getError("validIntergral不能为空");
			}
			if (false == this.isValid("totalIntergral", json)) {
				return this.getError("totalIntergral不能为空");
			}
			CrmBrandInfo brandInfo = crmBrandInfoService.getCrmBrandInfo(this.getMapValue("brand", json));
			if (brandInfo == null) {
				return this.getError("品牌不存在");
			}

			CustPointRecord entity = new CustPointRecord();
			entity.setMemberId(this.getMapValue("memberId", json));
			entity.setMobile(this.getMapValue("mobile", json));
			entity.setChangeId(this.getMapValue("changeId", json));
			String points = this.getMapValue("value", json);
			if (!StringUtil.isNullOrEmpty(points)) {
				entity.setPoints(Integer.valueOf(points));
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String getTime = this.getMapValue("getDate", json);
			if (!StringUtil.isNullOrEmpty(getTime)) {
				entity.setGetTime(sdf.parse(getTime));
			}
			String expiredDate = this.getMapValue("expiredDate", json);
			if (!StringUtil.isNullOrEmpty(expiredDate)) {
				entity.setExpiredTime(sdf.parse(expiredDate));
			}
			entity.setSource(this.getMapValue("changeReason", json));

			String validIntergral = this.getMapValue("validIntergral", json);
			if (!StringUtil.isNullOrEmpty(validIntergral)) {
				entity.setAvaPoints(Integer.valueOf(validIntergral));
			}
			String totalIntergral = this.getMapValue("totalIntergral", json);
			if (!StringUtil.isNullOrEmpty(totalIntergral)) {
				entity.setTotalPoints(Integer.valueOf(totalIntergral));
			}

			WxMediaPlatform mp = this.getMPWithAccessToken(brandInfo.getMpId());
			if (mp != null) {
				int rows = custPointRecordService.saveCustPointRecord(entity, mp);

				if (rows == -1) {
					return new AccessResponse<Object>("-1", "错误：该会员不存在。");
				}
				return new AccessResponse<Object>("0", "ok");
			} else {
				return this.getError("微信授权失败");
			}
		} else {
			return this.getError("数据格式无效");
		}

	}

	/**
	 * 会员卡券数据接收
	 * 
	 * @param map
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "SendCouponInfo", method = RequestMethod.POST)
	public Object sendCouponInfo(@RequestBody Map<String, Object> map, HttpServletRequest request)
			throws ParseException {
		JSONObject validSecret = validSecret(map);
		if (validSecret != null) {
			return validSecret;
		}

		if (false == this.isValid("couponJSONList", map)) {
			return this.getError("couponJSONList不能为空");
		}
		Map<String, Object> json = (Map<String, Object>) (map.get("couponJSONList"));
		if (json != null) {

			if (false == this.isValid("brand", json)) {
				return this.getError("brand不能为空");
			}
			if (false == this.isValid("memberId", json)) {
				return this.getError("memberId不能为空");
			}
			if (false == this.isValid("couponCode", json)) {
				return this.getError("couponCode不能为空");
			}
			if (false == this.isValid("couponName", json)) {
				return this.getError("couponName不能为空");
			}
			if (false == this.isValid("couponTempleID", json)) {
				return this.getError("couponTempleID不能为空");
			}
			if (false == this.isValid("couponType", json)) {
				return this.getError("couponType不能为空");
			}
			if (false == this.isValid("isUsed", json)) {
				return this.getError("isUsed不能为空");
			}
			CrmBrandInfo brandInfo = crmBrandInfoService.getCrmBrandInfo(this.getMapValue("brand", json));
			if (brandInfo == null) {
				return this.getError("品牌不存在");
			}

			CustCouponRecord entity = new CustCouponRecord();
			entity.setMemberId(this.getMapValue("memberId", json));
			entity.setMobile(this.getMapValue("mobile", json));
			entity.setCouponNo(this.getMapValue("couponCode", json));
			entity.setName(this.getMapValue("couponName", json));

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String startDate = this.getMapValue("startDate", json);
			if (!StringUtil.isNullOrEmpty(startDate)) {
				entity.setExpiredStartTime(sdf.parse(startDate));
			}
			String expiredDate = this.getMapValue("expiredDate", json);
			if (!StringUtil.isNullOrEmpty(expiredDate)) {
				entity.setExpiredEndTime(sdf.parse(expiredDate));
			}
			String isUsed = this.getMapValue("isUsed", json);
			if (!StringUtil.isNullOrEmpty(isUsed)) {
				entity.setIsUsed(Integer.valueOf(isUsed));
			}
			entity.setTemplateId(this.getMapValue("couponTempleID", json));
			String couponType = this.getMapValue("couponType", json);
			if (couponType.equalsIgnoreCase("eccoupon")) {
				entity.setTemplateId("ECCOUPON");
				entity.setCouponType("官网券");
			} else if (couponType.equalsIgnoreCase("storecoupon")) {
				entity.setCouponType("门店券");
			} else {
				entity.setCouponType(couponType);
			}

			WxMediaPlatform mp = this.getMPWithAccessToken(brandInfo.getMpId());
			if (mp != null) {
				int rows = couponService.saveCustCouponRecord(entity, mp);

				if (rows == -1) {
					return new AccessResponse<Object>("-1", "错误：该会员不存在。");
				}
				return new AccessResponse<Object>("0", "ok");
			} else {
				return this.getError("微信授权失败");
			}
		} else {
			return this.getError("数据格式无效");
		}

	}

	/**
	 * 优惠券模版数据接收
	 * 
	 * @param map
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "PushCouponTemplate", method = RequestMethod.POST)
	public Object pushCouponTemplate(@RequestBody Map<String, Object> map, HttpServletRequest request)
			throws ParseException {
		JSONObject validSecret = validSecret(map);
		if (validSecret != null) {
			return validSecret;
		}

		if (false == this.isValid("templateJSONList", map)) {
			return this.getError("templateJSONList不能为空");
		}
		Map<String, Object> json = (Map<String, Object>) (map.get("templateJSONList"));
		if (json != null) {

			if (false == this.isValid("brand", json)) {
				return this.getError("brand不能为空");
			}
			if (false == this.isValid("templateId", json)) {
				return this.getError("templateId不能为空");
			}
			if (false == this.isValid("name", json)) {
				return this.getError("name不能为空");
			}
			if (false == this.isValid("ruleDesc", json)) {
				return this.getError("ruleDesc不能为空");
			}
			if (false == this.isValid("couponType", json)) {
				return this.getError("couponType不能为空");
			}
			if (false == this.isValid("price", json)) {
				return this.getError("price不能为空");
			}
			if (false == this.isValid("status", json)) {
				return this.getError("status不能为空");
			}
			if (false == this.isValid("startTime", json)) {
				return this.getError("startTime不能为空");
			}
			if (false == this.isValid("endTimeType", json)) {
				return this.getError("endTimeType不能为空");
			}
			String endTimeType = this.getMapValue("endTimeType", json);
			if (endTimeType.equals("1")) { // 固定结束日期
				if (false == this.isValid("endTime", json)) {

					return this.getError("endTime不能为空");
				}
			} else if (endTimeType.equals("2")) {// 不固定结束日期

				if (false == this.isValid("dateUnit", json)) {
					return this.getError("dateUnit不能为空");
				}
				if (false == this.isValid("dateNum", json)) {
					return this.getError("dateNum不能为空");
				}
			}
			CrmBrandInfo brandInfo = crmBrandInfoService.getCrmBrandInfo(this.getMapValue("brand", json));
			if (brandInfo == null) {
				return this.getError("品牌不存在");
			}

			WxCardConfig entity = new WxCardConfig();
			entity.setMpId(brandInfo.getMpId());
			entity.setTemplateId(this.getMapValue("templateId", json));
			entity.setName(this.getMapValue("name", json));
			entity.setRuleDesc(this.getMapValue("ruleDesc", json));

			// couponType 有五个值 eccoupon(官网),1（现金）,2（折扣）,3（满减）,4（满折）
			String couponType = this.getMapValue("couponType", json);
			if (couponType.equals("1") || couponType.equals("3")) {
				entity.setCardType(DanskinConstants.WX_CARD_CONFIG_CARD_TYPE_CASH);
			} else if (couponType.equals("2") || couponType.equals("4")) {
				entity.setCardType(DanskinConstants.WX_CARD_CONFIG_CARD_TYPE_DISCOUNT);
			} else if (couponType.equalsIgnoreCase("eccoupon")) {
				entity.setCardType(DanskinConstants.WX_CARD_CONFIG_CARD_TYPE_ECCOUPON);
			}
			entity.setFaceValue(new BigDecimal(this.getMapValue("price", json)));
			String status = this.getMapValue("status", json);
			if (!StringUtil.isNullOrEmpty(status)) {
				entity.setStatus(Integer.valueOf(status));
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String startTime = this.getMapValue("startTime", json);
			if (!StringUtil.isNullOrEmpty(startTime)) {
				entity.setStartTime(sdf.parse(startTime));
			}

			Integer endTimeTypeValue = Integer.valueOf(endTimeType);

			if (endTimeTypeValue == 1) {
				String endTime = this.getMapValue("endTime", json);
				if (!StringUtil.isNullOrEmpty(endTime)) {
					entity.setExpiredTime(sdf.parse(endTime));
				}
			} else if (endTimeTypeValue == 2) {
				String dateUnit = this.getMapValue("dateUnit", json);
				String dateNum = this.getMapValue("dateNum", json);
				Integer dateNumValue = Integer.valueOf(dateNum);
				if (dateUnit.equals("1")) {// 1：天；2：月；3：年；
					entity.setExpiredTime(DateTools.getDateTools().operationDate(entity.getStartTime(), dateNumValue));
				} else if (dateUnit.equals("2")) {
					entity.setExpiredTime(DateTools.getDateTools().operationMonth(entity.getStartTime(), dateNumValue));
				} else if (dateUnit.equals("3")) {
					entity.setExpiredTime(DateTools.getDateTools().operationYear(entity.getStartTime(), dateNumValue));
				}
			}
			WxMediaPlatform mp = this.getMPWithAccessToken(brandInfo.getMpId());
			if (mp != null) {

				int rows = cardConfigService.saveCouponConfig(entity, mp);

				if (rows == -1) {
					return new AccessResponse<Object>("-1", "无效的凭证。");
				}
				return new AccessResponse<Object>("0", "ok");
			} else {
				return this.getError("微信授权失败");
			}
		} else {
			return this.getError("数据格式无效");
		}

	}

	/*
	 * 测试crm创建会员接口，for压测
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "CreateCrmMember", method = RequestMethod.POST)
	public Object createCrmMember(@RequestBody Map<String, Object> map, HttpServletRequest request) {
		JSONObject validSecret = validSecret(map);
		if (validSecret != null) {
			return validSecret;
		}
		if (false == this.isValid("memberJSONList", map)) {
			return this.getError("memberJSONList不能为空");
		}
		Map<String, Object> json = (Map<String, Object>) (map.get("memberJSONList"));
		if (json != null) {
			if (false == this.isValid("brand", json)) {
				return this.getError("brand不能为空");
			}
			if (false == this.isValid("mobileNum", json)) {
				return this.getError("mobileNum不能为空");
			}
			CrmBrandInfo brandInfo = crmBrandInfoService.getCrmBrandInfo(this.getMapValue("brand", json));
			if (brandInfo == null) {
				return this.getError("品牌不存在");
			}

			int rows = custInfoService.createMemberInfo(brandInfo, this.getMapValue("mobileNum", json));
			if (rows == -1) {
				return this.getError("调用CRM创建会员接口失败。");
			}
			return new AccessResponse<Object>("0", "ok");
		} else {
			return this.getError("数据格式无效");
		}
	}

	/**
	 * 测试crm推送积分数据接口，for压测
	 * 
	 * @param map
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "SendCustPoint", method = RequestMethod.POST)
	public Object sendCustPoint(@RequestBody Map<String, Object> map, HttpServletRequest request) {
		JSONObject validSecret = validSecret(map);
		if (validSecret != null) {
			return validSecret;
		}
		if (false == this.isValid("changeJSONList", map)) {
			return this.getError("changeJSONList不能为空");
		}
		Map<String, Object> json = (Map<String, Object>) (map.get("changeJSONList"));
		if (json != null) {

			if (false == this.isValid("brand", json)) {
				return this.getError("brand不能为空");
			}
			if (false == this.isValid("memberId", json)) {
				return this.getError("memberId不能为空");
			}
			if (false == this.isValid("mobile", json)) {
				return this.getError("mobile不能为空");
			}
			if (false == this.isValid("value", json)) {
				return this.getError("value不能为空");
			}
			if (false == this.isValid("changeReason", json)) {
				return this.getError("changeReason不能为空");
			}
			CrmBrandInfo brandInfo = crmBrandInfoService.getCrmBrandInfo(this.getMapValue("brand", json));
			if (brandInfo == null) {
				return this.getError("品牌不存在");
			}
			String changeId = BeanUtil.createOrderNumber();
			String memberId = this.getMapValue("memberId", json);
			String mobile = this.getMapValue("mobile", json);
			float value = Float.valueOf(this.getMapValue("value", json));
			String changeReason = this.getMapValue("changeReason", json);
			JSONObject result = DanskinCRMApiClient.createInstance().sendPointToCRM(changeId, memberId, mobile, value,
					changeReason, brandInfo.getBrandId());
			return new AccessResponse<Object>("0", "ok", result.toJSONString());
		} else {
			return this.getError("数据格式无效");
		}
	}

	/**
	 * 测试crm推送积分换券接口，for压测
	 * 
	 * @param map
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "PointBuyCoupon", method = RequestMethod.POST)
	public Object pointBuyCoupon(@RequestBody Map<String, Object> map, HttpServletRequest request) {
		JSONObject validSecret = validSecret(map);
		if (validSecret != null) {
			return validSecret;
		}
		if (false == this.isValid("buyJSONList", map)) {
			return this.getError("buyJSONList不能为空");
		}
		Map<String, Object> json = (Map<String, Object>) (map.get("buyJSONList"));
		if (json != null) {

			if (false == this.isValid("brand", json)) {
				return this.getError("brand不能为空");
			}
			if (false == this.isValid("memberId", json)) {
				return this.getError("memberId不能为空");
			}
			if (false == this.isValid("mobile", json)) {
				return this.getError("mobile不能为空");
			}
			if (false == this.isValid("templateId", json)) {
				return this.getError("templateId不能为空");
			}
			if (false == this.isValid("points", json)) {
				return this.getError("points不能为空");
			}
			if (false == this.isValid("num", json)) {
				return this.getError("num不能为空");
			}
			CrmBrandInfo brandInfo = crmBrandInfoService.getCrmBrandInfo(this.getMapValue("brand", json));
			if (brandInfo == null) {
				return this.getError("品牌不存在");
			}
			String memberId = this.getMapValue("memberId", json);
			String mobile = this.getMapValue("mobile", json);
			Integer points = Integer.valueOf(this.getMapValue("points", json));
			Integer num = Integer.valueOf(this.getMapValue("num", json));
			String templateId = this.getMapValue("templateId", json);

			CRMMemberRequest crmMember = new CRMMemberRequest();
			crmMember.setMemberId(memberId);
			crmMember.setMobile(mobile);
			crmMember.setBrandId(brandInfo.getBrandId());
			JSONObject result = DanskinCRMApiClient.createInstance().pointBuyCoupon(crmMember, templateId, num, points);

			return new AccessResponse<Object>("0", "ok", result.toJSONString());
		} else {
			return this.getError("数据格式无效");
		}
	}

	/**
	 * 测试crm优惠券发放接口，for压测
	 * 
	 * @param map
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "SendCustCoupon", method = RequestMethod.POST)
	public Object sendCustCoupon(@RequestBody Map<String, Object> map, HttpServletRequest request) {
		JSONObject validSecret = validSecret(map);
		if (validSecret != null) {
			return validSecret;
		}
		if (false == this.isValid("sendCouponList", map)) {
			return this.getError("sendCouponList不能为空");
		}
		Map<String, Object> json = (Map<String, Object>) (map.get("sendCouponList"));
		if (json != null) {

			if (false == this.isValid("brand", json)) {
				return this.getError("brand不能为空");
			}
			if (false == this.isValid("memberId", json)) {
				return this.getError("memberId不能为空");
			}
			if (false == this.isValid("templateId", json)) {
				return this.getError("templateId不能为空");
			}
			if (false == this.isValid("campaginName", json)) {
				return this.getError("campaginName不能为空");
			}
			if (false == this.isValid("num", json)) {
				return this.getError("num不能为空");
			}
			CrmBrandInfo brandInfo = crmBrandInfoService.getCrmBrandInfo(this.getMapValue("brand", json));
			if (brandInfo == null) {
				return this.getError("品牌不存在");
			}
			String memberId = this.getMapValue("memberId", json);
			String campaginName = this.getMapValue("campaginName", json);
			Integer num = Integer.valueOf(this.getMapValue("num", json));
			String templateId = this.getMapValue("templateId", json);

			JSONObject result = DanskinCRMApiClient.createInstance().sendCouponToCRM(memberId, templateId, num,
					campaginName, brandInfo.getBrandId());

			return new AccessResponse<Object>("0", "ok", result.toJSONString());
		} else {
			return this.getError("数据格式无效");
		}
	}

	/**
	 * 验证密钥
	 * 
	 * @param map
	 * @return
	 */
	private JSONObject validSecret(Map<String, Object> map) {
		LogUtil.info("crm调用接口参数：" + map.toString());

		if (false == this.isValid("signdate", map)) {
			return this.getError("signdate不能为空");
		}
		if (false == this.isValid("secret", map)) {
			return this.getError("secret不能为空");
		}
		String signdate = map.get("signdate").toString();
		Date date = DateUtils.str2Date(signdate, DateUtils.datetimeFormat);
		if (date == null) {
			return this.getError("无效的signdate");
		}
		String md5Secret = EncryptUtil.MD5((date.getTime() / 1000) + CRM_API_SECRET).toLowerCase();
		String secret = map.get("secret").toString();
		if (false == md5Secret.equals(secret)) {
			return this.getError("签名失败");
		}
		return null;
	}
}
